﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace JuCloudy.Platform.Structure.UI
{
    public partial class MainPage:JuCloudy.Framework.Interface.ISkin 
    {
        public MainPage()
        {
            InitializeComponent();

            this.Loaded += (obj, e) =>
            {
                JuCloudy.Framework.Storge.Session.Client["StructureUI"] = this;
            };
        }

        private JuCloudy.Framework.Interface.IStructure Structure =
                    (JuCloudy.Framework.Interface.IStructure)Application.Current.RootVisual;
        
        private ObservableCollection<JuCloudy.Data.Entity.SysStructure> Structures
        {
            get
            {
                return  new ObservableCollection<Data.Entity.SysStructure>(
                    ((List<Data.Entity.SysStructure>)JuCloudy.Framework.Storge.Session.Client["Structures"]).OrderBy(p => p.StructureOrder).ToList());
            }
        }

        private ObservableCollection<JuCloudy.Data.Entity.SysCategory> Categories
        {
            get
            {
                return new ObservableCollection<Data.Entity.SysCategory>(
                    ((List<Data.Entity.SysCategory>)JuCloudy.Framework.Storge.Session.Client["Categories"]).OrderBy(p => p.CategoryOrder).ToList());
            }
        }

        private ObservableCollection<JuCloudy.Data.Entity.SysAppInfo> AppInfos
        {
            get
            {
                return new ObservableCollection<Data.Entity.SysAppInfo>((List<Data.Entity.SysAppInfo>)JuCloudy.Framework.Storge.Session.Client["AppInfos"]);
            }
        }

        private bool IsPostBack = false;

        private void btn_setting_Click(object sender, RoutedEventArgs e)
        {
            ShowSettingDialog();
        }
        
        public void InitStructureItems()
        {
            var entities = Structures.TakeWhile(p => p.IsVisable == true);
            foreach (var entity in entities)
            {
                var item = new ComboBoxItem()
                {
                    Tag = entity.StructureId,
                    Content = entity.StructureHeader
                };
                this.select_Structure.Items.Add(item);
            }
            this.select_Structure.SelectedIndex = 0;
        }

        public void InitMenu(int StructureId)
        {
            var cates = from c in Categories
                        where c.StructureId == StructureId && c.IsVisable==true
                        select c;

            this.g_menu.Children.Clear();
            foreach (var entity in cates)
            {                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
                JuCloudy.Platform.UserControls.jListBox list = new Platform.UserControls.jListBox()
                {
                     Margin=new Thickness(0,0,1,0)
                };
                var query = from c in AppInfos
                            where c.CategoryId == entity.CategoryId
                            select c;
                foreach (var q in query)
                {
                    var jttm=new JuCloudy.Platform.UserControls.jListBoxItem()
                    {
                        Content = q.AppName,
                        Tag = q.AppId,
                        Padding = new Thickness(25, 5, 0, 5),
                        Cursor = Cursors.Hand
                    };
                    if(q.AppMainPageName=="ROOTPAGE"){
                        jttm.Tag="R"+q.AppId;
                    }
                    list.Items.Add(jttm);
                }

                if (query.Count() > 0)
                {
                    list.SelectionChanged += (obj, e) =>
                    {
                        if (e.AddedItems.Count > 0)
                        {
                            var item = e.AddedItems[0] as JuCloudy.Platform.UserControls.jListBoxItem;
                            foreach (var sitems in this.g_menu.Children)
                            {
                                if (sitems is JuCloudy.Platform.UserControls.jListBox && sitems != list)
                                {
                                    ((JuCloudy.Platform.UserControls.jListBox)sitems).SelectedItem = null;
                                }
                            }
                            if (item.Tag.ToString().Contains("R"))
                            {
                                this.ShowCustomRoot(int.Parse(item.Tag.ToString().Replace("R", "")));
                            }
                            else
                            {
                                this.InitApp((int)item.Tag);
                            }
                        }
                    };
                    this.g_menu.Children.Add(new TextBlock() { FontSize = 14, Text = entity.CategoryName, Padding = new Thickness(15, 5, 0, 5) });
                    this.g_menu.Children.Add(list);
                }
            }
            Structure.CloseLoading();
        }

        private void select_Structure_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                ComboBoxItem item = this.select_Structure.SelectedItem as ComboBoxItem;
                InitMenu((int)item.Tag);
            }
        }

        private void InitApp(int AppId)
        {
            Structure.ShowLoading();
            SystemService.WSSysServiceSoapClient client =
                           new SystemService.WSSysServiceSoapClient();
            client.GetAppInfoEntityAsync(AppId);
            client.GetAppInfoEntityCompleted += (obj, ex) =>
            {
                if (ex.Error != null)
                    throw ex.Error;
                var AppInfo = ex.Result.Deserialize(typeof(JuCloudy.Data.Entity.SysAppInfo))
                    as JuCloudy.Data.Entity.SysAppInfo;
                client.GetNewestAppModuleEntityAsync(AppId);
                client.GetNewestAppModuleEntityCompleted += (objn, exn) =>
                {
                    if (exn.Error != null)
                        throw exn.Error;

                    var appmodule=exn.Result.Deserialize(typeof(JuCloudy.Data.Entity.SysAppModule))
                        as JuCloudy.Data.Entity.SysAppModule;

                    this.txt_appname.Text = AppInfo.AppName;
                    this.txt_appintroduction.Text = AppInfo.AppIntroduction;
                    this.txt_brumb.Text = "首页>";
                    this.txt_brumb.Text += this.Categories.First(p => p.CategoryId == AppInfo.CategoryId).CategoryName+">";
                    this.txt_brumb.Text += AppInfo.AppName;
                    Structure.InitializeXap(AppInfo, appmodule, this.MainRoot);
                };
            };
        }

        private void btn_updatadiary_MouseEnter(object sender, MouseEventArgs e)
        {
            this.p_backlayer.Visibility = Visibility.Visible;
        }

        private void btn_updatadiary_MouseLeave(object sender, MouseEventArgs e)
        {
            this.p_backlayer.Visibility = Visibility.Collapsed;
        }

        public UIElement GetStructureSeletorContainer()
        {
            return this.select_Structure;
        }

        public UIElement GetMenuContainer()
        {
            return g_menu;
        }

        public TextBlock GetBrumbControl()
        {
            return txt_brumb;
        }

        public TextBlock GetAppNameControl()
        {
            return txt_appname;
        }

        public TextBlock GetAppintroduction()
        {
            return txt_appintroduction;
        }

        public Grid GetMainRootContainer()
        {
            return MainRoot;
        }

        public void ShowSettingDialog()
        {
            Structure.ShowChildDialog(new Module.SystemSetting(), "设置");
        }

        public void ShowDefaultRoot()
        {
            this.DefaultRoot.Visibility = Visibility.Visible;
            this.CustomRoot.Visibility = Visibility.Collapsed;
            this.CustomRoot.Children.Clear();
        }

        public void ShowCustomRoot(int AppId)
        {
            Structure.ShowLoading();
            SystemService.WSSysServiceSoapClient client =
                           new SystemService.WSSysServiceSoapClient();
            client.GetAppInfoEntityAsync(AppId);
            client.GetAppInfoEntityCompleted += (obj, ex) =>
            {
                if (ex.Error != null)
                    throw ex.Error;
                var AppInfo = ex.Result.Deserialize(typeof(JuCloudy.Data.Entity.SysAppInfo))
                    as JuCloudy.Data.Entity.SysAppInfo;
                client.GetNewestAppModuleEntityAsync(AppId);
                client.GetNewestAppModuleEntityCompleted += (objn, exn) =>
                {
                    if (exn.Error != null)
                        throw exn.Error;


                    var appmodule = exn.Result.Deserialize(typeof(JuCloudy.Data.Entity.SysAppModule))
                        as JuCloudy.Data.Entity.SysAppModule;

                    Structure.ShowCustomRoot(AppInfo, appmodule);
                };
            };
            this.DefaultRoot.Visibility = Visibility.Collapsed;
            this.CustomRoot.Visibility = Visibility.Visible;
        }

        public void InitResources(EventHandler OnCompleted)
        {
            SystemService.WSSysServiceSoapClient client =
                new SystemService.WSSysServiceSoapClient();
            //加载架构数据
            client.GetCategoryEntitiesCompleted += (obj, e) =>
            {
                if (e.Error != null)
                    throw e.Error;
                else
                {
                    JuCloudy.Framework.Storge.Session.Client["Categories"] = e.Result.Deserialize(typeof(List<JuCloudy.Data.Entity.SysCategory>));
                    if (!IsPostBack)
                    {
                        //载入架构下拉框数据
                        InitStructureItems();

                        IsPostBack = true;

                        if (OnCompleted != null)
                        {
                            OnCompleted.Invoke(obj, e);
                        }
                    }
                }
            };

            client.GetAppInfoEntitiesCompleted += (obj, e) => 
            {
                if (e.Error != null)
                    throw e.Error;
                else
                {
                    JuCloudy.Framework.Storge.Session.Client["AppInfos"] = e.Result.Deserialize(typeof(List<JuCloudy.Data.Entity.SysAppInfo>));
                    client.GetCategoryEntitiesAsync();
                }
            };

            client.GetStructureEntitiesAsync();            
            client.GetStructureEntitiesCompleted += (obj, e) =>
            {
                if (e.Error != null)
                    throw e.Error;
                else
                {
                    JuCloudy.Framework.Storge.Session.Client["Structures"] = e.Result.Deserialize(typeof(List<JuCloudy.Data.Entity.SysStructure>));
                    client.GetAppInfoEntitiesAsync();
                }
            };

        }
    }

    public class PropertyComparer<T> : IEqualityComparer<T>
    {
        private PropertyInfo _PropertyInfo;

        /// <summary>
        /// 通过propertyName 获取PropertyInfo对象    
        /// </summary>
        /// <param name="propertyName"></param>
        public PropertyComparer(string propertyName)
        {
            _PropertyInfo = typeof(T).GetProperty(propertyName,
            BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public);
            if (_PropertyInfo == null)
            {
                throw new ArgumentException(string.Format("{0} is not a property of type {1}.",
                    propertyName, typeof(T)));
            }
        }

        #region IEqualityComparer<T> Members

        public bool Equals(T x, T y)
        {
            object xValue = _PropertyInfo.GetValue(x, null);
            object yValue = _PropertyInfo.GetValue(y, null);

            if (xValue == null)
                return yValue == null;

            return xValue.Equals(yValue);
        }

        public int GetHashCode(T obj)
        {
            object propertyValue = _PropertyInfo.GetValue(obj, null);

            if (propertyValue == null)
                return 0;
            else
                return propertyValue.GetHashCode();
        }

        #endregion
    }
 
}
